package org.bunny.vehicle.service.admin;

import java.util.Date;

import org.bunny.vehicle.entity.Vehicle;
import org.bunny.vehicle.service.BaseService;
import org.bunny.vehicle.util.Const;
import org.bunny.vehicle.util.JSON;
import org.bunny.vehicle.util.Utils;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.spring.SpringCreator;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@RemoteProxy(creator = SpringCreator.class)
@Service
public class AdminVehicleService extends BaseService {

	public Page<Vehicle> getList(String json) {
		JSONObject obj = JSON.parseObject(json);

		byte type = JSON.getByte(obj, "type");
		int page = JSON.getInteger(obj, "page");

		return vehicleRepository.findByClassification(type, new PageRequest(page, Const.PAGE_SIZE,
				Sort.Direction.DESC, "id"));
	}

	public boolean del(String json) {
		try {
			JSONArray array = JSONArray.parseArray(json);

			for (Object obj : array) {
				vehicleRepository.delete(Integer.parseInt(obj.toString()));
			}
		} catch (Exception e) {
			log.error(e + json, e);
			return false;
		}
		return true;
	}

	public boolean save(String json) {
		JSONObject obj = JSON.parseObject(json);

		byte classification = JSON.getByte(obj, "classification");
		int id = JSON.getInteger(obj, "id");
		String priceString = JSON.getString(obj, "price");
		String licensePlate = JSON.getString(obj, "licensePlate");
		String model = JSON.getString(obj, "model");
		String frameNumber = JSON.getString(obj, "frameNumber");
		String engineNumber = JSON.getString(obj, "engineNumber");
		Date registrationDate = JSON.getDate(obj, "registrationDateYear", "registrationDateMonth",
				"registrationDateDate");
		Date buyDate = JSON.getDate(obj, "buyDateYear", "buyDateMonth", "buyDateDate");

		if (Utils.isEmpty(licensePlate)) {
			return false;
		}

		Vehicle vehicle;
		if (id > 0) {
			vehicle = vehicleRepository.findOne(id);
			if (null == vehicle) {
				return false;
			}
		} else {
			vehicle = new Vehicle();
		}
		vehicle.setBuyDate(buyDate);
		vehicle.setClassification(classification);
		vehicle.setEngineNumber(engineNumber);
		vehicle.setFrameNumber(frameNumber);
		vehicle.setLicensePlate(licensePlate);
		vehicle.setModel(model);
		vehicle.setPrice(Utils.stringToMoney(priceString));
		vehicle.setRegistrationDate(registrationDate);
		return null != vehicleRepository.save(vehicle);
	}

}
